package com.scu.bank.configurer;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scu.bank.core.cache.SystemCache;
import com.scu.bank.core.cache.impl.GuavaCache;
import com.scu.bank.core.cache.impl.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PostConstruct;

@Configuration
public class CacheServiceConfig {
    @Value(value="${token.validity.time:#{30}}")
    private int tokenTime;
    @Value(value="${login.failed.time:#{24*60}}")
    private int loginFailedTime;
    @Value(value="${spring.redis.host:#{null}}")
    private String redisHost;

    private static Logger logger = LoggerFactory.getLogger(CacheServiceConfig.class);

    @PostConstruct
    public void init() {
        logger.info("The current SystemCache use {}", redisHost == null ? "guava cache" : "redis cache, the host is " + this.redisHost);
    }

    @Bean
    public SystemCache userCacheService() {
        return this.redisHost == null ? new GuavaCache(this.tokenTime) :
                new RedisCache(this.tokenTime, "LoginCache");
    }

    @Bean
    @ConditionalOnExpression("#{environment['spring.redis.host'] != null}")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        template.setValueSerializer(jacksonSeial);
        template.setKeySerializer(new StringRedisSerializer());

        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }


}
